package com.cangxuan.backend.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cangxuan.backend.bean.Result;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 视图工具类
 */
public class ViewUtils {

    /**
     * 向响应写入内容，用于返回给客户端
     * @param response
     * @param status
     * @param message
     */
    public static void print(HttpServletResponse response, int status, String message) {
        print(response, status, message, null);
    }


    /**
     * 向响应写入内容，用于返回给客户端
     * @param response
     * @param status
     * @param message
     * @param value
     */
    public static void print(HttpServletResponse response, int status, String message, Object value) {
        response.setStatus(status);
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        PrintWriter printWriter;
        try {
            printWriter = response.getWriter();     //获取响应的“打印笔”
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Result result = new Result(status, message, value);
        printWriter.write(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
        printWriter.flush();
        printWriter.close();
    }

}
